package com.sniper.model;

import com.sniper.constants.DataValues;
import com.sniper.util.DataUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * @author suzhen
 * @create 2018/2/13
 */
public class BaseToStringEntity implements BaseModelAble {

    private static final long serialVersionUID = -7039789941119033975L;

    @Override
    @SuppressWarnings({"rawtypes"})
    public String toString() {
        try {
            Map<Class, Boolean> dataType = DataValues.dataType();
            StringBuilder buffer = new StringBuilder();
            Class clazz = this.getClass();
            String simpleName = clazz.getSimpleName();
            buffer.append(simpleName);
            buffer.append("{");
            Field[] superFs = clazz.getSuperclass().getDeclaredFields();
            Field[] fs = clazz.getDeclaredFields();
            //父级和本地合并
            Field[] fields = DataUtil.concat(superFs, fs);
            Class fType;
            String fName;
            Object fValue;
            for (Field f : fields) {
                fType = f.getType();
                fName = f.getName();
                // 设置私有属性可读可访问
                f.setAccessible(true);
                // 判断基本数据类型,过滤静态
                if (Modifier.isStatic(f.getModifiers())) {
                    continue;
                }

                fValue = f.get(this);
                // 判断基本数据类型,过滤静态
                //TODO 判断是否是原始类型 fType.isPrimitive()
                if (dataType.containsKey(fType)) {
                    buffer.append(fName);
                    buffer.append(":");
                    buffer.append(fType);
                    buffer.append(",");
                    buffer.append(fValue).append(";");
                }
            }

            buffer.append("}");
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
